package com.dx.mes.common.dao.impl;

import static com.dx.mes.common.bean.def.GenericDef.E_BIS_STOCKER;
import static com.dx.mes.common.bean.def.GenericDef.E_COMMON_RTD_IS_SPACE;
import static com.dx.mes.common.bean.def.GenericDef.E_COMMON_RTD_NO_PARTITION;
import static com.dx.mes.common.bean.def.GenericDef.E_COMMON_RTD_NO_STOCKER;
import static com.dx.mes.common.bean.def.GenericDef.E_COMMON_RTD_NO_ZONE;
import static com.dx.mes.common.bean.def.GenericDef.E_COMMON_RTD_PARTITION_FULL;
import static com.dx.mes.common.bean.def.GenericDef.E_COMMON_RTD_ZONE_FULL;
import static com.dx.mes.common.bean.def.GenericDef.E_READ_NOT_FOUND;
import static com.dx.mes.common.bean.def.GenericDef.E_RET_STOCKER_PTN;
import static com.dx.mes.common.bean.def.GenericDef.E_RET_STOCKER_ST;
import static com.dx.mes.common.bean.def.GenericDef.E_RET_STOCKER_ZN;
import static com.dx.mes.common.bean.def.GenericDef.E_RET_TOOL_PT;
import static com.dx.mes.common.bean.def.GenericDef.RTD_XFR_CMD_FLG_STI;
import static com.dx.mes.common.bean.def.GenericDef.RTD_XFR_CMD_FLG_SXS;
import static com.dx.mes.common.bean.def.GenericDef.RTD_XFR_CMD_FLG_TXT;
import static com.dx.mes.common.bean.def.GenericDef._NORMAL;

import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.dx.common.table.ppt.Bis_stocker;
import com.dx.common.table.ppt.Ret_box_xfr;
import com.dx.common.table.ppt.Ret_stocker_ptn;
import com.dx.common.table.ppt.Ret_stocker_st;
import com.dx.common.table.ppt.Ret_stocker_zn;
import com.dx.common.table.ppt.Ret_tool_pt;
import com.dx.common.table.ppt.Ret_tool_ptId;
import com.dx.mes.common.core.dao.impl.GenericHibernateDao;
import com.dx.mes.common.dao.IBisStockerDao;
import com.dx.mes.common.dao.IRetBoxXfrDao;
import com.dx.mes.common.dao.IRetStockerPtnDao;
import com.dx.mes.common.dao.IRetStockerStDao;
import com.dx.mes.common.dao.IRetStockerZnDao;
import com.dx.mes.common.dao.IRetToolPtDao;
import com.dx.mes.common.table.rtnBean.SimpleRtnBeen;
import com.dx.mes.common.table.rtnBean.rtd.StockerBeen;
import com.dx.mes.common.table.rtnBean.rtd.StockerPatiBeen;
import com.dx.mes.common.table.rtnBean.rtd.StockerZoneBeen;
import com.dx.mes.common.transcoder.util.Util;

@Repository
public class BisStockerHibernateDao extends GenericHibernateDao<Bis_stocker, String> 
implements IBisStockerDao{
	private Logger logger = Logger.getLogger(BisStockerHibernateDao.class);
	@Autowired
	private IRetToolPtDao retToolPtDao;
	@Autowired
	private IRetStockerStDao retStockerStDao;
	@Autowired
	private IRetStockerPtnDao retStockerPtnDao;
	@Autowired
	private IRetStockerZnDao retStockerZnDao;
	@Autowired
	private IRetBoxXfrDao retBoxXfrDao;
	
	/**
	 * Load Return Stocker Information
	 */
	public SimpleRtnBeen comStkInLoadReturnPati(String tool_id, String port_id){
		SimpleRtnBeen rtnBeen = new SimpleRtnBeen(_NORMAL);
		List<StockerBeen> stockerBeenList = new ArrayList<StockerBeen>();
		
		Ret_tool_ptId tool_ptId = new Ret_tool_ptId();
		tool_ptId.setTool_id_fk(tool_id);
		tool_ptId.setPort_id(port_id);
		Ret_tool_pt ret_tool_pt = retToolPtDao.get(tool_ptId);
		if(ret_tool_pt == null){
			return new SimpleRtnBeen(E_RET_TOOL_PT + E_READ_NOT_FOUND,
					"未找到设备[" + tool_id
					+ "],端口[" + port_id
					+ "]信息[RET_TOOL_PT]");
		}else if(Util.isSpaceCheck(ret_tool_pt.getTo_stk_id())){
			return new SimpleRtnBeen(E_COMMON_RTD_IS_SPACE,
					"设备[" + tool_id
					+ "],端口[" + port_id
					+ "]未维护返回Stocker[RET_TOOL_PT][TO_STK_ID]");
		}
		
		//获取return stocker
		Bis_stocker bis_stocker = this.get(ret_tool_pt.getTo_stk_id());
		if(bis_stocker != null){
			rtnBeen = this.comStkInSumStockInCrr(ret_tool_pt.getTo_stk_id(), null);
			if(rtnBeen.getlRc() != _NORMAL){
				return rtnBeen;
			}else{
				StockerBeen stockerBeen = (StockerBeen) rtnBeen.getObj();
				stockerBeenList.add(stockerBeen);
				return new SimpleRtnBeen(stockerBeenList);
			}
		}
		
		//TODO 获取Stocker Group 预留
		
		return new SimpleRtnBeen(_NORMAL);
	}
	
	/**
	 * Sum Carrier Use Count Of Stocker'sPartition & Zone
	 */
	public SimpleRtnBeen comStkInSumStockInCrr(String stocker_id, List<Ret_box_xfr>  box_xfrList){
		SimpleRtnBeen rtnBeen = new SimpleRtnBeen(_NORMAL);
		StockerBeen stockerBeen = new StockerBeen();
		rtnBeen = this.comStkInLoadStocker(stocker_id);
		if(rtnBeen.getlRc() != _NORMAL){
			return rtnBeen;
		}else{
			stockerBeen = (StockerBeen) rtnBeen.getObj();
		}
		
		if(box_xfrList == null){
			box_xfrList = new ArrayList<Ret_box_xfr>();
			//获取卡匣List（Stocker In 的卡匣 & 从Stocker搬走但位置没变更的卡匣  & 已经产生搬送至Stocker指令的卡匣都算）
			box_xfrList = retBoxXfrDao.find("FROM Ret_box_xfr WHERE xfr_pos_id='" + stocker_id
					+ "' OR xfr_to_tool_id='" + stocker_id + "'");
			if(box_xfrList.size() == 0){
				logger.info("未找到Stocker[" + stocker_id + "]的卡匣搬送信息[RET_BOX_XFR]");
			}
		}
		
//		List<Ret_box_xfr>  box_xfrList = retBoxXfrDao.find("FROM Ret_box_xfr WHERE xfr_pos_id='" + stocker_id
//				+ "' OR xfr_to_tool_id='" + stocker_id + "'");
//		if(box_xfrList.size() == 0){
//			return new SimpleRtnBeen(E_RET_BOX_XFR + E_READ_NOT_FOUND, 
//					"未找到Stocker[" + stocker_id + "]的卡匣搬送信息[RET_BOX_XFR]");
//		}
		
		//TODO Sum Carrier use Count In Stocker（预留，暂时不需要）
		
		//Sum Carrier Use Count In Partition
		for(StockerPatiBeen patiBeen:stockerBeen.getStkPatiList()){
			for(Ret_box_xfr box_xfr:box_xfrList){
				if(RTD_XFR_CMD_FLG_STI.equals(box_xfr.getXfr_cmd_flg())){
					if(stockerBeen.getStocker_id().equals(box_xfr.getXfr_pos_id()) &&
							patiBeen.getPati_id().equals(box_xfr.getXfr_pati_id())){
						patiBeen.setPati_use_qty(patiBeen.getPati_use_qty() + 1);
					}
				}else if(RTD_XFR_CMD_FLG_SXS.equals(box_xfr.getXfr_cmd_flg()) ||
						RTD_XFR_CMD_FLG_TXT.equals(box_xfr.getXfr_cmd_flg())){
					if(stockerBeen.getStocker_id().equals(box_xfr.getXfr_pos_id()) && 
							patiBeen.getPati_id().equals(box_xfr.getXfr_pati_id())){
						patiBeen.setPati_use_qty(patiBeen.getPati_use_qty() + 1);
					}else if(stockerBeen.getStocker_id().equals(box_xfr.getXfr_to_tool_id()) && 
							patiBeen.getPati_id().equals(box_xfr.getXfr_to_pati_id())){
						patiBeen.setPati_use_qty(patiBeen.getPati_use_qty() + 1);
					}
				}
			}
		}
		
		//Sum Carrier Use Count In Zone
		for(StockerZoneBeen zoneBeen:stockerBeen.getStkZoneList()){
			for(Ret_box_xfr box_xfr:box_xfrList){
				if(RTD_XFR_CMD_FLG_STI.equals(box_xfr.getXfr_cmd_flg())){
					if(stockerBeen.getStocker_id().equals(box_xfr.getXfr_pos_id()) &&
							zoneBeen.getZone_id().equals(box_xfr.getXfr_zone_id())){
						zoneBeen.setZone_use_qty(zoneBeen.getZone_use_qty() + 1);
					}
				}else if(RTD_XFR_CMD_FLG_SXS.equals(box_xfr.getXfr_cmd_flg()) ||
						RTD_XFR_CMD_FLG_TXT.equals(box_xfr.getXfr_cmd_flg())){
					if(stockerBeen.getStocker_id().equals(box_xfr.getXfr_pos_id()) && 
							zoneBeen.getZone_id().equals(box_xfr.getXfr_zone_id())){
						zoneBeen.setZone_use_qty(zoneBeen.getZone_use_qty() + 1);
					}else if(stockerBeen.getStocker_id().equals(box_xfr.getXfr_to_tool_id()) && 
							zoneBeen.getZone_id().equals(box_xfr.getXfr_to_zone_id())){
						zoneBeen.setZone_use_qty(zoneBeen.getZone_use_qty() + 1);
					}
				}
			}
		}
		
		
		return new SimpleRtnBeen(stockerBeen);
	}
	
	/**
	 * Load Information Of Stocker's Partition & Zone 
	 */
	public SimpleRtnBeen comStkInLoadStocker(String stocker_id){
		StockerBeen stockerBeen = new StockerBeen();
		
		//获取Stocker信息
		Bis_stocker bis_stocker = this.get(stocker_id);
		if(bis_stocker == null){
			return new SimpleRtnBeen(E_BIS_STOCKER + E_READ_NOT_FOUND,
					"未找到Stocker[" + stocker_id
					+ "]信息[BIS_STOCKER]");
		}
		
		Ret_stocker_st ret_stocker_st = retStockerStDao.get(stocker_id);
		if(ret_stocker_st == null){
			return new SimpleRtnBeen(E_RET_STOCKER_ST + E_READ_NOT_FOUND, 
					"未找到Stocker[" + stocker_id + "]设定信息[RET_STOCKER_ST]");
		}
		
		stockerBeen.setStocker_id(stocker_id);
		stockerBeen.setShelf_total_cnt(bis_stocker.getTotal_shelf_cnt() != null ? bis_stocker.getTotal_shelf_cnt() : 0);
		stockerBeen.setShelf_use_cnt(0);//TODO 预留
		stockerBeen.setStocker_threshold(ret_stocker_st.getStocker_threshold() != null ? ret_stocker_st.getStocker_threshold() : 0);
		stockerBeen.setStocker_clean_time(ret_stocker_st.getStocker_clean_time() != null ? ret_stocker_st.getStocker_clean_time() : 0);
		
		//获取Stocker Partition设定
		List<Ret_stocker_ptn> stocker_ptnList = retStockerPtnDao.find("FROM Ret_stocker_ptn WHERE stocker_id_fk='"
				+ stocker_id + "'");
		if(stocker_ptnList.size() == 0){
			return new SimpleRtnBeen(E_RET_STOCKER_PTN + E_READ_NOT_FOUND, 
					"未找到Stocker[" + stocker_id + "]的Partition信息[RET_STOCKER_PTN]");
		}
		List<StockerPatiBeen> patiBeenList = new ArrayList<StockerPatiBeen>();
		for(Ret_stocker_ptn stocker_ptn:stocker_ptnList){
			StockerPatiBeen patiBeen = new StockerPatiBeen();
			patiBeen.setPati_id(stocker_ptn.getId().getPati_id());
			patiBeen.setPati_max_qty(stocker_ptn.getPati_max_cnt() != null ? stocker_ptn.getPati_max_cnt() : 0);
			patiBeen.setPati_use_qty(0);
			patiBeenList.add(patiBeen);
		}
		
		stockerBeen.setPati_cnt(patiBeenList.size());
		stockerBeen.setStkPatiList(patiBeenList);
		
		//获取Stocker Zone设定
		List<Ret_stocker_zn> stocker_znList = retStockerZnDao.find("FROM Ret_stocker_zn WHERE stocker_id_fk='"
				+ stocker_id + "'");
		if(stocker_znList.size() == 0){
			return new SimpleRtnBeen(E_RET_STOCKER_ZN + E_READ_NOT_FOUND, 
					"未找到Stocker[" + stocker_id + "]的Zone信息[RET_STOCKER_ZN]");
		}	
		List<StockerZoneBeen> zoneBeenList = new ArrayList<StockerZoneBeen>();
		for(Ret_stocker_zn sorcker_zn:stocker_znList){
			StockerZoneBeen zoneBeen = new StockerZoneBeen();
			zoneBeen.setZone_id(sorcker_zn.getId().getZone_id());
			zoneBeen.setZone_dsc(sorcker_zn.getZone_dsc());
			zoneBeen.setZone_std_qty(sorcker_zn.getZone_std_qty() != null ? sorcker_zn.getZone_std_qty() : 0);
			zoneBeen.setZone_use_qty(0);
			zoneBeenList.add(zoneBeen);
		}
		stockerBeen.setZone_cnt(zoneBeenList.size());
		stockerBeen.setStkZoneList(zoneBeenList);
		
		return new SimpleRtnBeen(stockerBeen);
	}
	
	public SimpleRtnBeen comStkInCheckStcUsage(List<StockerBeen> stockerBeenList, String stocker_id, 
			String pati_id, String zone_id){
		Integer ix = 0;
		Integer iy = 0;
		Integer iz = 0;
		
		for(ix=0; ix<stockerBeenList.size(); ix++){
			StockerBeen stockerBeen = stockerBeenList.get(ix);
			if(stockerBeen.getStocker_id().equals(stocker_id)){
				
				//检查partition
				if(!Util.isSpaceCheck(pati_id)){
					for(iy=0; iy<stockerBeen.getStkPatiList().size(); iy++){
						StockerPatiBeen patiBeen = stockerBeen.getStkPatiList().get(iy);
						if(pati_id.equals(patiBeen.getPati_id())){
							if(patiBeen.getPati_use_qty() >= patiBeen.getPati_max_qty()){
								return new SimpleRtnBeen(E_COMMON_RTD_PARTITION_FULL, 
										"Stocker[" + stocker_id + "]Partition[" + pati_id
										+ "]使用数量超过最大设定数量。Used Count[" + patiBeen.getPati_use_qty()
										+ "]，Max Count[" + patiBeen.getPati_max_qty() + "]");
							}
							break;
						}
					}
					
					if(iy == stockerBeen.getStkPatiList().size()){
						return new SimpleRtnBeen(E_COMMON_RTD_NO_PARTITION, 
								"No Partition ID[" + stocker_id + "][" + pati_id + "]");
					}
				}
				
				//检查zone
				if(!Util.isSpaceCheck(zone_id)){
					for(iz=0; iz<stockerBeen.getStkZoneList().size(); iz++){
						StockerZoneBeen zoneBeen = stockerBeen.getStkZoneList().get(iz);
						if(zone_id.equals(zoneBeen.getZone_id())){
							if(zoneBeen.getZone_use_qty() >= zoneBeen.getZone_std_qty()){
								return new SimpleRtnBeen(E_COMMON_RTD_ZONE_FULL, 
										"Stocker[" + stocker_id + "]Zone[" + zone_id
										+ "]使用数量超过最大设定数量。Used Count[" + zoneBeen.getZone_use_qty()
										+ "]，Max Count[" + zoneBeen.getZone_std_qty() + "]");
							}
							break;
						}
					}
					
					if(iz == stockerBeen.getStkZoneList().size()){
						return new SimpleRtnBeen(E_COMMON_RTD_NO_ZONE, 
								"No Zone ID[" + stocker_id + "][" + zone_id + "]");
					}
				}
				
				break;
			}
		}
		
		if(ix == stockerBeenList.size()){
			return new SimpleRtnBeen(E_COMMON_RTD_NO_STOCKER, 
					"No Stocker ID[" + stocker_id + "]");
		}
		
		return new SimpleRtnBeen(_NORMAL);
	}
}
